package com.example.springboot01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot01.constant.Constants;
import com.example.springboot01.model.TokenModel;
import com.example.springboot01.model.UserToken;
import com.example.springboot01.service.TokenManageService;
import com.example.springboot01.service.UserTokenService;
import com.example.springboot01.utils.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * Token管理接口的数据库实现类
 * @Auther: zrd
 * @Date: 2022/6/5/06/05/16:20
 * @Description: com.example.springboot01.service.impl
 */
@Service
public class TokenManageServiceDBImpl implements TokenManageService {
    @Autowired
    UserTokenService userTokenService;
    // 创建token
    @Override
    public String createToken(String userId, String userType) {
        //校验用户id是否存在
        UserToken userToken = userTokenService.getOne(new QueryWrapper<UserToken>()
                .eq("user_id" ,userId));
        //如果不存在则创建
        LocalDateTime nowTime = LocalDateTime.now();
        boolean operSucc = false;
        if (userToken == null){
            userToken = new UserToken();
            userToken.setId(UUIDUtil.getUUID());
            userToken.setTokenValue(UUIDUtil.getUUID());
            userToken.setUserId(userId);
            userToken.setUserType(userType);
            userToken.setUpdateTime(nowTime);
            operSucc = userTokenService.save(userToken);
        }else {

            //如果存在则更新
            userToken.setTokenValue(UUIDUtil.getUUID());
            userToken.setUpdateTime(nowTime);
            userToken.setUserId(null);
            userToken.setUserType(null);
            operSucc = userTokenService.updateById(userToken);
        }
        if (!operSucc){
            return null;
        }
        //生成token返回
        String token = userId + "_" + userType + "_" + userToken.getTokenValue();
        return token;
    }


    //校验token
    @Override
    public boolean checkToken(String token) {
        TokenModel tokenModel = extractToken(token);
        if(tokenModel == null){
            return false;
        }
        //去数据库检查是否存在相同的用户id和token值
        List<UserToken> tokenList = userTokenService.list(new QueryWrapper<UserToken>()
                .eq("user_id",tokenModel.getUserId())
                .eq("token_value",tokenModel.getTokenValue())
                .gt("update_time",LocalDateTime.now().minusMinutes(Constants.TOKEN_EXPIRED_TIME_MIN)));
        if (tokenList != null && tokenList.size() > 0){
            return true;
        }
        return false;
    }
    //解析token
    @Override
    public TokenModel extractToken(String token) {
        String[] params = token.split("_");
        if(params.length < 3){
            return null;
        }
        TokenModel tokenModel = new TokenModel();
        tokenModel.setUserId(params[0]);
        tokenModel.setUserType(params[1]);
        tokenModel.setTokenValue(params[2]);
        return tokenModel;
    }

    //根据token获取用户id
    @Override
    public String getUserIdFromToken(String token) {
        TokenModel tokenModel = extractToken(token);
        if (tokenModel == null || StringUtils.isEmpty(tokenModel.getUserId())){
            return null;
        }
        return tokenModel.getUserId();
    }

    //删除token
    @Override
    public boolean deleteToken(String token) {
        TokenModel tokenModel = extractToken(token);
        if (tokenModel == null || StringUtils.isEmpty(tokenModel.getUserId())){
            return false;
        }
        //更新数据库，把userid对应的token记录的tokenvalue置空
        UserToken userToken = new UserToken();
        userToken.setTokenValue("");
        boolean operSucc = userTokenService.update(userToken,new QueryWrapper<UserToken>()
                .eq("user_id",tokenModel.getUserId()));
        return operSucc;
    }
}
